// pages/cart/index/index.js
const Controllers = require('../../controllers/Controller.js').controller;
const app = getApp();


var startPoint
Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalStype: '',
    isSelectAll: false,
    total: 0,
    sum: 0,
    allPrice: 0,
    tabbar: [],
    shopId: '',
    cartList: [],
    invalidList: [],
    isReturn: false,
    tabBottom: 132,
    clickMe: true,
    buttonRight: 0,
    buttonBottom: 0,
    couponAccountId:''
  },


  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0] //获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1] //获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint //重置开始位置
    var buttonBottom = this.data.buttonBottom - translateY
    var buttonRight = this.data.buttonRight - translateX
    //判断是移动否超出屏幕
    if (buttonRight + 50 >= this.data.windowWidth) {
      buttonRight = this.data.windowWidth - 50;
    }
    if (buttonRight <= 0) {
      buttonRight = 0;
    }
    if (buttonBottom <= 0) {
      buttonBottom = 0
    }
    if (buttonBottom + 50 >= this.data.windowHeight) {
      buttonBottom = this.data.windowHeight - 50;
    }
    this.setData({
      buttonBottom: buttonBottom,
      buttonRight: buttonRight
    })
  },
  buttonEnd: function (e) {},

  //获取手机型号改变操作栏
  getPhoneInfo() {
    let _self = this
    wx.getSystemInfo({
      success: function (res) {
        let model = res.model;
        if (model.search('iPhone X') != -1 || model.search('iPhone 11') != -1 || model.search('iPhone 12') != -1) {
          console.log("是大屏手机")
          _self.setData({
            tabBottom: 200
          })
        }
      }
    })
  },

  //获取购物车列表
  getCartList() {
    //获取数据
    Controllers.cartList({
      shopId: this.data.shopId
    }).then(res => {
      console.log("res", res)
      let invalidList = res.data.invalid
      let cartList = res.data.normal
      cartList.forEach(item => {
        item.select = false
      })
      let calc = this.calculateprice(cartList)
      this.setData({
        invalidList,
        cartList,
        allPrice: calc.allPrice,
        sum: calc.sum,
        total: calc.total
      })
    })
  },


  //跳转详情
  goDetail(e) {
    let url = e.currentTarget.dataset['url'];
    wx.navigateTo({
      url: url
    })
  },
  //跳转提交订单
  goPage() {
    let list
    list = this.data.cartList.filter(item => item.select)
    if (list.length > 0) {
      list = encodeURIComponent(JSON.stringify(list))
      wx.navigateTo({
        url: '/pages/cart/submitOrder/submitOrder?list=' + list  + '&couponAccountId=' + this.data.couponAccountId,
      })
    } else {
      wx.showToast({
        title: "请选择商品",
        icon: 'none',
        duration: 800
      });
    }
  },
  //删除商品
  deleteCart(e) {
    let index = e.currentTarget.dataset['index'];
    let ids
    this.setData({
      isSelectAll: false
    })
    if (index == "all") {
      ids = []
      this.data.cartList.forEach(item => {
        if (item.select) {
          ids.push(item.id)
        }
      })
      ids = ids.join(",")
    } else {
      ids = this.data.cartList[index].id
    }
    if (!ids) {
      wx.showToast({
        icon: "none",
        title: '请选择删除商品',
      })
      return
    }
    wx.showModal({
      title:"是否删除该商品",
      success:(res)=>{
        if(res.confirm){
          Controllers.delGoods({
            shopId: this.data.shopId,
            cartIds: ids
          }).then(res => {
            if (res.code == 1) {
              this.getCartList()
            }
          })
        }
      }
    })
    
  },
  //选择商品
  selectGood(e) {
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let isSelectAll
    cartList[index].select = !cartList[index].select;
    for (let i = 0; i < cartList.length; i++) {
      if (!cartList[i].select) {
        isSelectAll = false
        break
      } else {
        isSelectAll = true
      }
    }
    let calc = this.calculateprice(cartList)
    this.setData({
      cartList,
      isSelectAll,
      allPrice: calc.allPrice,
      sum: calc.sum,
      total: calc.total
    })
  },
  //加减商品数量
  addSubtract(e) {
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    if (type == "add") {
      cartList[index].num += 1
    } else if (cartList[index].num > 1) {
      cartList[index].num -= 1
    }
    let calc = this.calculateprice(cartList)
    Controllers.updateCart({
      shopId: this.data.shopId,
      cartId: cartList[index].id,
      num: cartList[index].num
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          cartList: cartList,
          allPrice: calc.allPrice,
          sum: calc.sum,
          total: calc.total
        })
      }
    })
  },
  //加减失效商品数量
  addInvalidListSubtract(e) {
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let invalidList = this.data.invalidList;
    if (type == "add") {
      invalidList[index].num += 1
    } else if (invalidList[index].num > 1) {
      invalidList[index].num -= 1
    }
    Controllers.updateCart({
      shopId: this.data.shopId,
      cartId: invalidList[index].id,
      num: invalidList[index].num
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          invalidList: invalidList
        })
      }
    })
  },
  //全选
  selectAll() {
    let isSelectAll = this.data.isSelectAll
    isSelectAll = !isSelectAll
    let cartList = this.data.cartList;
    cartList.forEach(item => {
      if (isSelectAll) {
        item.select = true
      } else {
        item.select = false
      }
    })
    let calc = this.calculateprice(cartList)
    this.setData({
      cartList,
      isSelectAll,
      allPrice: calc.allPrice,
      sum: calc.sum,
      total: calc.total
    })
  },

  //取消全选
  cancleSelect() {
    let isSelectAll = this.data.isSelectAll
    isSelectAll = false
    let cartList = this.data.cartList;
    cartList.forEach(item => {
      item.select = false
    })
    let calc = this.calculateprice(cartList)
    this.setData({
      cartList,
      isSelectAll,
      allPrice: calc.allPrice,
      sum: calc.sum,
      total: calc.total
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      globalStype: app.globalData.globalStype
    })
    this.getPhoneInfo()
    if (app.globalData.shopId) {
      this.setData({
        shopId: app.globalData.shopId
      })
    }
    let isReturn = false
    if (options.isReturn == 1) {
      isReturn = true
    }
    if(options.couponAccountId){
      this.setData({
        couponAccountId:options.couponAccountId
      })
    }
    console.log("isReturn", isReturn)
    this.setData({
      isReturn,
      tabbar: this.data.globalStype == 'pinStyle' ? app.globalData.tabbar : app.globalData.tabbar2,
    })

    let that = this
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 屏幕宽度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 高度,宽度 单位为px
        that.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth,
          buttonBottom: 250, //这里定义按钮的初始位置
          buttonRight: 0, //这里定义按钮的初始位置
        })
      }
    })

  },

  myInformation() {
    //获取数据
    Controllers.myInformation({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        myInformationdata: res.data.accountRelation
      })
      this.getCartList()
    }).catch(res => {
      this.getCartList()
    })
  },
  onShow() {
    this.myInformation()
    this.cancleSelect()
  },
  changenums(e) {
    
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let calc = this.calculateprice(cartList)

    let num=Number(e.detail.value)
    if(!num||num<=0)num=1
    cartList[index].num = num

    Controllers.updateCart({
      shopId: this.data.shopId,
      cartId: cartList[index].id,
      num: cartList[index].num
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          cartList: cartList,
          allPrice: calc.allPrice,
          sum: calc.sum,
          total: calc.total
        })
      }
    })
  },

  toClickMe() {
    wx.navigateTo({
      url: '/pages/clickMe/clickMe',
    })
  },

  cancleClickMe() {
    this.setData({
      clickMe: false
    })
  },


  // 计算商品总价
  calculateprice(cartList) {
    let sum = 0
    let total = 0
    let allPrice = 0
    console.log(123);
    let vip = this.data.myInformationdata.vip 
    cartList.forEach(item => {
      // 用户处于对应身份且商品开启对应价格
      var price = 0;
      if (item.openAgent && item.agentPrice) {
        price = item.agentPrice;
      } else if (item.openShareholder && item.shareholderPrice) {
        price = item.shareholderPrice;
      } else if ((vip == 1 || vip == 3 || vip == 4) && item.vipState && item.vipPrice >= 0) {
        price = item.vipPrice;
      } else if (vip != 0 && item.memberState && item.memberPrice >= 0) {
        price = item.memberPrice;
      } else {
        price = item.price;
      }
      if (item.select) {
        sum += item.num
        total += item.num * price
        allPrice += item.num * item.price
      }
    })
    return {
      allPrice,
      sum,
      total
    }
  }
})